const jwt = require('jsonwebtoken')
const { createUser, getUerInfo,updateById } = require('../service/user.service')
const {userRegisterError} = require('../consitant/err.type')
const {JWT_SECRET} = require('../config/config.default')
class UserController {
  async register(ctx, next) {

   try{
    const { user_name, password } = ctx.request.body
    const user_res = await createUser(user_name, password)
   
    ctx.body = {
      code: 0,
      message: '用户注册成功',
      result: {
        id: user_res.id,
        user_name: user_res.user_name,
      },
    }
   }catch(err){

    console.log(err)
    ctx.app.emit('error',userRegisterError,ctx)

   }

  }

  async login(ctx, next) {
    const {user_name} = ctx.request.body;
      //获取用户信息（在token中的playload中，记录id，user_name，is_admin）
      try{

        //返回结果对象中剔除掉password属性，将剩下的属性放到res对象中间
        const res = await getUerInfo({user_name})
        const {password,...resUser} = res
        ctx.body = {
          code:'0',
          message:`登录成功`,
          result:{
            id: res.id,
            user_name: res.user_name,
            token:jwt.sign(resUser,JWT_SECRET,{expiresIn:'1d'})
          }
        }
      }catch(err){
        console.error('用户登录失败',err)
      }

  }

  async setpossword(ctx,next) {
    try{

      const id = ctx.state.user.id
      const password = ctx.request.body.password
      const res = await updateById({id,password})
      if(res){
        ctx.body = {
          code:'0',
          message:'修改密码成功',
          result:''
        }
      }
    }catch(err){
      ctx.body = {
        code:'10007',
        message:'修改密码失败',
        result:"为什么失败我也不知道你去看看吧"
      }
    }
  }
}

module.exports = new UserController()
